﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Web.Routing;

namespace Vit.Web.Mvc.DataAnnotations
{
    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public class DependOnAttribute : ValidationAttribute, IClientValidatable
    {
        public DependOnAttribute(string dependOnProperty, string action, string controller)
            : this(dependOnProperty, action, controller, null)
        {
        }

        public DependOnAttribute(string dependOnProperty, string action, string controller, string area)
        {
            RouteData = new RouteValueDictionary();
            RouteData["controller"] = controller;
            RouteData["action"] = action;
            if (!string.IsNullOrWhiteSpace(area))
                RouteData["area"] = area;
            DependOnProperty = dependOnProperty;
        }

        public override bool IsValid(object value)
        {
            return true;
        }

        protected RouteValueDictionary RouteData { get; set; }
        public string DependOnProperty { get; set; }
        public string AdditionalFields { get; set; }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            ModelClientValidationRule rule = new ModelClientValidationRule()
                {
                    ErrorMessage = ErrorMessage,
                    ValidationType = "dependon"
                };

            rule.ValidationParameters["dependon"] = DependOnProperty;
            rule.ValidationParameters["action"] = RouteData["action"];
            rule.ValidationParameters["controller"] = RouteData["controller"];
            if (RouteData.ContainsKey("area"))
                rule.ValidationParameters["area"] = RouteData["area"];
            else
                rule.ValidationParameters["area"] = null;
            if(!string.IsNullOrWhiteSpace(AdditionalFields))
                rule.ValidationParameters["additionalfields"] = AdditionalFields;

            yield return rule;
        }
    }
}
